<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" title="角色权限管理"> 在此页面进行角色维护 </n-card>
    </div>
    <n-card :bordered="false" class="mt-4 proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
      >
        <template #tableTitle>
          <n-button type="primary" @click="addRole">
            <template #icon>
              <n-icon>
                <PlusOutlined />
              </n-icon>
            </template>
            添加角色
          </n-button>
        </template>

        <template #action>
          <TableAction />
        </template>
      </BasicTable>
    </n-card>

    <n-modal v-model:show="showAddModal" :show-icon="false" preset="dialog" :title="editRoleTitle">
      <n-form
        :model="formParams"
        :rules="rules"
        ref="formRef"
        label-placement="left"
        :label-width="80"
        class="py-4"
      >
        <n-form-item label="角色名称" path="roleName">
          <n-input placeholder="请输入角色名称" v-model:value="formParams.roleName" />
        </n-form-item>
        <n-form-item label="描述" path="description">
          <n-input
            type="textarea"
            placeholder="请输入描述"
            v-model:value="formParams.description"
          />
        </n-form-item>
        <n-form-item label="角色编码" path="roleCode">
          <n-input placeholder="请输入角色名称" v-model:value="formParams.roleCode" />
        </n-form-item>
      </n-form>

      <template #action>
        <n-space>
          <n-button @click="() => (showAddModal = false)">取消</n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmRoleForm">确定</n-button>
        </n-space>
      </template>
    </n-modal>

    <n-modal
      v-model:show="showModal"
      :show-icon="false"
      preset="dialog"
      :title="editRolePermissionsTitle"
    >
      <div class="py-3 menu-list">
        <n-tree
          block-line
          cascade
          checkable
          key-field="identity"
          label-field="menuName"
          :virtual-scroll="true"
          :data="treeData"
          :expandedKeys="expandedKeys"
          :checked-keys="checkedKeys"
          style="max-height: 950px; overflow: hidden"
          @update:checked-keys="checkedTree"
          @update:expanded-keys="onExpandedKeys"
        />
      </div>
      <template #action>
        <n-space>
          <n-button type="info" ghost icon-placement="left" @click="packHandle">
            全部{{ expandedKeys.length ? '收起' : '展开' }}
          </n-button>

          <n-button type="info" ghost icon-placement="left" @click="checkedAllHandle">
            全部{{ checkedAll ? '取消' : '选择' }}
          </n-button>
          <n-button type="primary" :loading="formBtnLoading" @click="confirmForm">提交</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, unref, h, onMounted } from 'vue';
  import { useDialog, useMessage, TreeOption } from 'naive-ui';
  import { BasicTable, TableAction } from '@/components/Table';
  import {
    getRolePage,
    savePermissions,
    saveRole,
    updateRole,
    deleteRole,
  } from '@/api/system/role';
  import { getMenuTree } from '@/api/system/menu';
  import { columns } from './columns';
  import { PlusOutlined } from '@vicons/antd';
  import { getTreeAll } from '@/utils';
  import { ResultEnum } from '@/enums/httpEnum';

  const formRef: any = ref(null);
  const message = useMessage();
  const actionRef = ref();

  const showAddModal = ref(false);
  const showModal = ref(false);
  const formBtnLoading = ref(false);
  const checkedAll = ref(false);
  const editRoleTitle = ref('');
  const editRolePermissionsTitle = ref('');
  const treeData = ref([]);
  const expandedKeys = ref([]);
  const checkedKeys = ref(['console']);
  const checkedRoleId = ref(); //当前编辑权限的角色id
  const isEdit = ref(false); // 弹出框是否为编辑

  const params = reactive({});
  const dialog = useDialog();

  const rules = {
    roleName: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入角色名称',
    },
    description: {
      required: false,
      trigger: ['blur', 'input'],
      message: '请输入描述',
    },
    roleCode: {
      required: true,
      trigger: ['blur', 'change'],
      message: '请输入角色编码',
    },
  };

  const formParams = reactive({
    id: null,
    roleName: '',
    description: '',
    roleCode: '',
  });
  const formParamsBak = { ...formParams };

  const actionColumn = reactive({
    width: 250,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction, {
        style: 'button',
        actions: [
          {
            label: '菜单权限',
            onClick: handleMenuAuth.bind(null, record),
            // 根据业务控制是否显示 isShow 和 auth 是并且关系
            ifShow: () => {
              return true;
            },
            // 根据权限控制是否显示: 有权限，会显示，支持多个
            //auth: ['system_role'],
          },
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
            ifShow: () => {
              return true;
            },
            //auth: ['system_role'],
          },
          {
            label: '删除',
            icon: 'ic:outline-delete-outline',
            onClick: handleDelete.bind(null, record),
            // 根据业务控制是否显示 isShow 和 auth 是并且关系
            ifShow: () => {
              return true;
            },
            // 根据权限控制是否显示: 有权限，会显示，支持多个
            //auth: ['system_role'],
          },
        ],
      });
    },
  });

  const loadDataTable = async (res: any) => {
    let _params = {
      ...unref(params),
      ...res,
    };
    return await getRolePage(_params);
  };

  function onCheckedRow(rowKeys: any[]) {
    console.log(rowKeys);
  }

  function reloadTable() {
    actionRef.value.reload();
  }

  function addRole() {
    // 新增前清空表单
    Object.assign(formParams, formParamsBak);
    showAddModal.value = true;
    isEdit.value = false;
    editRoleTitle.value = '添加角色';
  }

  /**
   * 添加/编辑角色
   */
  function confirmRoleForm(e: any) {
    e.preventDefault();
    formBtnLoading.value = true;
    formRef.value.validate(async (errors: boolean) => {
      if (!errors) {
        let response;
        // 如果是编辑
        if (isEdit.value) {
          formParams.id = checkedRoleId.value;
          response = await updateRole(formParams);
        } else {
          response = await saveRole(formParams);
        }
        const { message: msg, code } = response;
        if (code == ResultEnum.SUCCESS) {
          message.success(msg);
          Object.assign(formParams, formParamsBak);
          showAddModal.value = false;
          reloadTable();
        } else {
          message.error(msg);
        }
      } else {
        message.error('请填写完整信息');
      }
      formBtnLoading.value = false;
    });
  }

  /**
   * 菜单权限编辑
   */
  async function confirmForm(e: any) {
    e.preventDefault();
    formBtnLoading.value = true;
    // 组成逗号隔开的字符
    const permissions = checkedKeys.value.join(',');
    const params = {
      id: checkedRoleId.value,
      permissions,
    };
    const { code, message: msg } = await savePermissions(params);
    if (code == ResultEnum.SUCCESS) {
      message.success(msg);
      reloadTable();
      showModal.value = false;
    } else {
      message.error(msg);
    }
    formBtnLoading.value = false;
  }

  function handleEdit(record: Recordable) {
    console.log('点击了编辑', record);
    checkedRoleId.value = record.id;
    editRoleTitle.value = `编辑角色-${record.roleName}`;
    Object.assign(formParams, record);
    showAddModal.value = true;
    isEdit.value = true;
  }

  async function handleDelete(record: Recordable) {
    console.log('点击了删除', record);
    dialog.info({
      title: '提示',
      content: `您确定想删除此角色吗?`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        const params = { id: record.id };
        const response = await deleteRole(params);
        const { message: msg, code } = response;
        if (code == ResultEnum.SUCCESS) {
          message.success(msg);
          reloadTable();
        } else {
          message.error(msg);
        }
      },
      onNegativeClick: () => {
        //message.error('已取消');
      },
    });
  }

  function handleMenuAuth(record: Recordable) {
    editRolePermissionsTitle.value = `分配 ${record.roleName} 的菜单权限`;
    checkedRoleId.value = record.id;
    if (record.permissions) {
      checkedKeys.value = record.permissions.split(',');
    } else {
      checkedKeys.value = [];
    }
    console.log('已有权限：', checkedKeys.value);
    showModal.value = true;
  }

  function checkedTree(keys, trees) {
    //console.log(keys, trees);
    let checkKyes: string[] = [];
    // 过滤掉1级菜单，不过滤的话，后续增加子菜单会默认也选中，误导人
    for (let tree of trees) {
      if (tree === null) {
        continue;
      }
      if (tree.pid != 0) {
        checkKyes.push(tree.identity);
      }
    }
    checkedKeys.value = checkKyes;
  }

  function onExpandedKeys(keys) {
    expandedKeys.value = keys;
  }

  function packHandle() {
    if (expandedKeys.value.length) {
      expandedKeys.value = [];
    } else {
      expandedKeys.value = treeData.value.map((item: any) => item.identity) as [];
    }
  }

  function checkedAllHandle() {
    if (!checkedAll.value) {
      checkedKeys.value = getTreeAll(treeData.value, 'identity');
      checkedAll.value = true;
    } else {
      checkedKeys.value = [];
      checkedAll.value = false;
    }
  }

  onMounted(async () => {
    const treeMenuList = await getMenuTree();
    expandedKeys.value = treeMenuList.map((item) => item.identity);
    treeData.value = treeMenuList;
  });
</script>

<style lang="less" scoped></style>
